<template>
<section class="container">
  <div class="row">
    <div class="col-md-5">
      <form @submit.prevent="postHandler">
        <div class="form-group">
          <label for="exampleInputEmail1">选择板块</label>
          <select class="form-control">
            <option>分享</option>
            <option>问答</option>
            <option>招聘</option>
            <option>客户端测试</option>
          </select>
        </div>
        <div class="form-group">
          <label for="title">标题</label>
          <input required v-model="formData.title" class="form-control" id="title">
        </div>
        <div class="form-group">
          <label for="content">内容</label>
          <textarea id="content" required v-model="formData.content" class="form-control" rows="3"></textarea>
        </div>
        <p>{{ errorMessage }}</p>
        <button type="submit" class="btn btn-default">Submit</button>
      </form>
    </div>
  </div>
</section>
</template>

<script>
import axios from 'axios'
import _ from 'lodash'

export default {
	data () {
		return {
			formData : {
				title : '',
				content : ''
			},
			errorMessage : ''
		}
	},
	created () {
		const {id} = this.$route.params
		this.loadTopic(id)
	},
	methods : {
		async loadTopic (id) {
			try {
				const {data : topic} = await axios.get(`/api/topics/${id}`)
				this.formData = topic
			} catch(err) {
				const {status, statusText, data} = err.response
				this.errorMessage = status + '|' + data.error
			}
		},
		postHandler : _.debounce (async function(){
			try {
				const id = this.formData.id
				const {data} = await axios.patch(`/api/topics/${id}`, this.formData)
				this.errorMessage = ''
				this.$router.push(`/topic/detail/${id}`)
			} catch(err) {
				console.log(err.response)
				const {status} = err.response
				switch (status) {
					case 401:
						this.errorMessage = '未授权'
						break;
				}
			}
		}, 500) 
	}
}
</script>

<style>
	
</style>
